package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.comment.dto.ApCommentVo;
import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentLikeDto;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentService;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadUtil;
import com.heima.common.util.SensitiveWordUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    GreenTextScan textScan;

    @Autowired
    UserFeign userFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    /*
        评论保存
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //判断是否登录(需要使用线程 -> 远程调用 -> 添加拦截器)
        User user = AppThreadUtil.getThread();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断评论内容是否大于140
        if (dto == null || StringUtils.isEmpty(dto.getContent()) || dto.getContent().length() > 140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //评论内容健康审查
        boolean result = audit(dto.getContent());
        if (result == false){
            //文本审核不通过
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存评论
        ApComment apComment = new ApComment();
        //用户id
        apComment.setAuthorId(user.getUserId());
        //根据id查询用户
        ResponseResult<ApUser> userFeignById = userFeign.getUserById(user.getUserId());
        if (userFeignById.getCode().equals(AppHttpCodeEnum.SUCCESS)){
            ApUser apUser = userFeignById.getData();
            //用户姓名
            apComment.setAuthorName(apUser.getName());
            //用户头像
            apComment.setImage(apUser.getImage());
        }
        //文章id或动态id
        apComment.setEntryId(dto.getArticleId());
        apComment.setChannelId(dto.getChannelId()); //频道id
        apComment.setType(0);   //评论的类型  0文章
        apComment.setContent(dto.getContent());     //评论的内容
        apComment.setLikes(0);      //评论初始点赞量
        apComment.setReply(0);      //评论初始回复量
        apComment.setFlag(0);       //评论等级
        apComment.setCreatedTime(new Date());   //发表评论的时间
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(apComment);
    }

    /*
        点赞功能实现
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //判断用户是否登录
        User user = AppThreadUtil.getThread();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //构建点赞记录
        ApCommentLike commentLike = new ApCommentLike();
        commentLike.setAuthorId(user.getUserId());
        commentLike.setCommentId(dto.getCommentId());
        commentLike.setOperation(dto.getOperation());

        //创建查询条件  判断当前用户是否已经对文章进行点赞
        Query query = new Query();
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        ApCommentLike one = mongoTemplate.findOne(query, ApCommentLike.class);
        int add = 0;
        if (one == null){
            //没有点赞  保存点赞记录
            if (dto.getOperation() == 0) {
                mongoTemplate.save(commentLike);
                add = 1;
            }
        }else {
            if (one.getOperation() != dto.getOperation()){
                //判断是点赞行为还是取消点赞行为
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                //点赞
                if (dto.getOperation() == 0){
                    add = 1;
                }else {
                    //取消点赞
                    add = -1;
                }
            }
        }
        //修改评论点赞量
        if (add != 0){
            //更新评论点赞量
            Query commentQuery = new Query();
            commentQuery.addCriteria(Criteria.where("id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes",add);
            mongoTemplate.updateFirst(commentQuery,update,ApComment.class);
        }
        return ResponseResult.okResult();
    }

    /*
        评论列表展示
     */
    @Override
    public ResponseResult load(CommentDto dto) {
        //判断用户是否登录
        User user = AppThreadUtil.getThread();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据文章id查询评论列表
        Query query = new Query();
        query.addCriteria(Criteria.where("entryId").is(dto.getArticleId()));
        //根据最小时间查询
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));

        //分页查询
        Pageable page = PageRequest.of(0,10, Sort.Direction.DESC,"createdTime");
        query.with(page);
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        List<ApCommentVo> vos = new ArrayList<>();
        //提取所有的评论id
        List ids = new ArrayList<>();
        for (ApComment apComment : apComments) {
            ApCommentVo vo = new ApCommentVo();
            BeanUtils.copyProperties(apComment,vo);
            vo.setOperation(1);
            vos.add(vo);
            ids.add(apComment.getId());
        }
        //判断当前用户在当前评论中是否已经点过赞   点过赞需要高亮显示
        Query likesQuery = new Query();
        likesQuery.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        likesQuery.addCriteria(Criteria.where("commentId").is(ids));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(likesQuery, ApCommentLike.class);
        //定义评论id集合
        List<String> likesId = new ArrayList<>();
        for (ApCommentLike apCommentLike : apCommentLikes) {
            if (apCommentLike.getOperation() == 0){
                likesId.add(apCommentLike.getCommentId());
            }
        }

        //变量结果列表
        for (ApCommentVo vo : vos) {
            if (likesId.contains(vo.getId())){
                vo.setOperation(0);
            }
        }
        return ResponseResult.okResult(vos);
    }



    /*
        自动审核评论内容是否合规
     */

    private boolean audit(String content) {
        boolean result = false;

        try {
            Map map = textScan.greenTextScan(content);
            // 判断结果
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "pass":
                    result = true;
                    break;
                case "block":
                    break;
                case "review":
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
